package com.kzw.dao;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.kzw.entity.Category;

import my.db.Page;
import my.db.QueryHelper;

/**
 * 文章的增删改查
 * */
public class CategoryDao {

	// 增加
	public void save(Category c) {
		String sql = "insert into category values(null,?,?)";
		QueryHelper.update(sql, c.getName(), c.getNt());
	}
	
	// 修改
	public void update(Category c) {
		String sql = "update category set name=?,nt=? where id=?";
		QueryHelper.update(sql, c.getName(), c.getNt(), c.getId());
	}
	
	// 删除
	public void delete(Long id) {
		String sql = "delete from category where id=?";
		QueryHelper.update(sql, id);
	}
	
	/**
	 * 根据ID查询
	 * */
	public Category get(Long id) {
		String sql = "select * from category where id=?";
		return QueryHelper.queryUnique(Category.class, sql, id);
	}
	
	/**
	 * 分页查询
	 * */
	public Page<Category> findPage(Page<Category> page, String name) {
		List<Object> params = new ArrayList<>();
		String sql = "select * from category";
		if(StringUtils.isNotBlank(name)) {
			sql += " where name like ?";
			params.add("%"+name+"%");
		}
		if(StringUtils.isNotBlank(page.getField())) {
			sql += String.format(" order by %s %s", page.getField(), page.getType());
		}
		
		List<Category> data = QueryHelper.queryPage(Category.class, sql, page.getPage(), page.getLimit(), params.toArray());
		page.setData(data);
		
		String sql2 = sql.replaceFirst("select .*? from", "select count(*) from");
		Long cnt = QueryHelper.stat(sql2, params.toArray());
		page.setCount(cnt);			
		
		return page;
	}
}
